/**
 * fancyplayer 1.0.0
 *
 * http://weibo.com/u/2718532847/home?wvr=5&sudaref=passport.weibo.com
 *
 * Copyright 2015, zhong
 * The fancyplayer
 *
 * Released on: December 1, 2015
 */
(function($) {

$.fn.extend({
	fancyPlayer: function(options) {

		// fancyplayer默认参数
		var defaults = {

			//fancyplayer头部
			header : true,

			//fancyplayer头部-消息
			msg : true,

			//fancyplayer头部-消息下拉框
			msgDropDown : true,

			//fancyplayer头部-卡片
			userCar : true,

			//fancyplayer头部-卡片下拉框
			userCarDropDown : true,

			//播放区域是视频(参数video)还是文档(参数pdf)
			player: null,

			//fancyplayer章节列表
			sectionList: true,

			//fancyplayer评论
			comment: true,

			//fancyplayer收藏
			attention: true,

			//fancyplayer分享
			share: true,

			//video时间点HH:mm:ss，弹出练习题，用","链接多个时间点;默认为没有时间点，值为false
			pointTime: "5"

		};

		var o = $.extend(defaults, options);

		// 给每一个fancyplayer实例化
		this.each(function(){

				// 当前fancyplayer容器
			var me = $(this),
				// window对象
				$window = $(window);
				// 当前fancyplayer头部
				$header = me.find('.course-detail-header'),
				// 当前fancyplayer消息
				$msg = me.find('.nvr-msg'),
				// 当前fancyplayer卡片
			    $userCar = me.find('.user-card-box'),
				// 当前fancyplayer卡片下拉框
				hasUserCardClass ='has-user-card',
			    $userCarDropDown = me.find('.g-user-card'),
				//fancyplayer视频区域
				$fancyPlayerBox = me.find('.fancyplayer-box-wrap'),
				//fancyplayer章节列表
				shapterVisible = o.sectionList,
				shapterHideClass = "hideList",
				shapterShowClass = "showList",
				$sectionList = me.find('.section-list'),
				$sectionWrap = me.find('.section-wrap'),
				$chapter = me.find('.chapter'),
				$slimscroll = me.find('.section-con'),
				//fancyplayer评论
				$comment = me.find('.comment'),
				//fancyplayer收藏
				$collect = me.find('.collect'),
				//fancyplayer分享
				$share = me.find('.share'),

				//练习题问答弹出框
				exercisesClick = $('#exercises-click'),
				exercisesModal = $('#video-exercises'),
				exercisesOptions = exercisesModal.find('.exercises-input'),
				exercisesLis = $(exercisesOptions).find('li'),
				exercisesChecked = "exercises-judge-checked",
				exercisesStandarded = "exercises-judge-standarded",
				exercisesUnable = $(exercisesModal).find('.unable'),
				exercisesSure = $(exercisesModal).find('.sure'),
				exercisesAnswerCorrect = exercisesModal.find('.exercises-answercorrect'),
				exercisesAnswerError = exercisesModal.find('.exercises-answererror'),

				//video
				videoPlayer = "",
				videoCurrentTime = 0,

				//pdf
				swfUrl = o.url;

			//初始化fancyplayer接口
			o.init = function(){
				//弹出框
				if(o.hasParam("video",o.player)){
					//video播放器
					var player = new MediaElementPlayer('#player',{
						enableAutosize: false,
						enablePluginSmoothing:true,
						enablePluginDebug: true,
						plugins: ['flash'],
						success: function(me) {
							o.videoPlayer = me;
							me.addEventListener('timeupdate', function() {
								o.videoCurrentTime = me.currentTime;
							}, false)
						}
					});
					//video时间点事件
					o.setVideoTimestampEvent();
					//IE、6、7、8下video装成FLASH后视频播放的处理
					$('.mejs-inner').on('click',function(){setTimeout(o.setFlashVideoSize,150)});
				}
				//PDF播放器
				if(o.hasParam("pdf",o.player)){
                    var i18n = {
                        file:
                        {
                           title: "Some document.pdf"
                        },
                        label:
                        {
                            actualSize: "实际大小",
                            fitPage: "适合页面",
                            fitWidth: "适合宽度",
                            fitHeight: "适合高度",
                            fullscreen: "全屏显示",
                            fullwindow: "最大化",
                            fullwindow_escape: "按ESC退出全屏模式",
                            page: "页码",
                            pageOf: "/"
                        },
                        errors: {
                            "error": "The content cannot be displayed due to an unknown error.",
                            "content": "The content cannot be displayed because it is not of type png, jpg, gif or swf.",
                            "io": "The preview could not be loaded from the server."
                        }
                    };
					var onPreviewEvent = function (event) {
						if (event.event) {
							var wrapper;
							if (event.event.type == "onFullWindowClick") {
							   // Called when "Maximize" button was clicked
							   wrapper = document.getElementById("wrapper");
							   wrapper.style.width = "100%";
							   wrapper.style.height = "100%";
							   wrapper.style.position = "absolute";
							} else if (event.event.type == "onFullWindowEscape") {
							   wrapper = document.getElementById("wrapper");
							   wrapper.style.width = "100%";
							   wrapper.style.height = "100%";
							   wrapper.style.position = "static";
							}
					 	} else if (event.error) {
							// Inform the user about the failure
							alert(i18n.errors[event.error.code] || "Error");
						}
					};
					var myPreviewLogger = function (msg, level) {
						if (console && console.log) {
							console.log("WebPreviewer [" + level + "]: " + msg);
						}
					};
					// Url to the result of the pdf2swf conversion (make sure the -T flag was turned on during the transformation)
					var url = "flash/small-webpreview.swf?noCache=" + (new Date().getTime());
					var flashvars =
					{
						fileName: i18n.file.title,
						paging: true,  // If false only 1 page is displayed at a time
						url: url,
						jsCallback: "onPreviewEvent", // Optional but needed if Maximize button shall work
						jsLogger: "myPreviewLogger", // Optional
						show_fullscreen_button: true, // Set to false to hide "Fullscreen" button
						show_fullwindow_button: false,	// Set to false to hide "Maximize" button
						disable_i18n_input_fix: false, // Set to true to stop fix from being sed if it causes problem for some reason
						i18n_actualSize: i18n.label.actualSize,
						i18n_fitPage: i18n.label.fitPage,
						i18n_fitWidth: i18n.label.fitWidth,
						i18n_fitHeight: i18n.label.fitHeight,
						i18n_fullscreen: i18n.label.fullscreen,
						i18n_fullwindow: i18n.label.fullwindow,
						i18n_fullwindow_escape: i18n.label.fullwindow_escape,
						i18n_page: i18n.label.page,
						i18n_pageOf: i18n.label.pageOf
					};
					var params =
					{
						allowScriptAccess: "sameDomain", // Allow JavaScript & ActionScript to connect
						allowFullScreen: "true", // To allow the "Fullscreen" button to work
						wmode: "transparent" // Remove if you don't plan to display html elements on top of the previewer (will increase performace slightly)
					};
					var attributes =
					{
						id: "previewer",
						name: "previewer" // Must match id to make extMouseWheel.js work (scrolling on MacOSX)
					};
					swfobject.embedSWF(swfUrl, "previewer", "100%", "100%", "9.0.124", false, flashvars, params, attributes);
				};
				//章节列表滚动条
				/*$slimscroll.slimscroll({
					height: '100%',
					color: '#536780'
				});*/
				//初始化fancyplayer显示容器区域
				o.setFancyPlayerBoxSize();
				//问答选择交互效果
				o.toggleExercises();

			};

			//头像下拉框-有与无
			if(o.userCarDropDown){
				$userCar.addClass(hasUserCardClass);
			} else {
				$userCar.removeClass(hasUserCardClass);
			};

			//问答练习题交互效果
			o.toggleExercises = function(){
				$(exercisesLis).bind('click',function(){
					if($(this).index()==0){
						var video = o.videoPlayer;
						//$(exercisesClose).addClass(exercisesCloseClass);
						$(exercisesLis).unbind('click').removeClass(exercisesChecked);
						$(this).addClass(exercisesStandarded + " " + exercisesChecked);
						$(exercisesUnable).hide();
						$(exercisesSure).show();
						$(exercisesAnswerCorrect).show();
						$(exercisesAnswerError).hide();
						$(exercisesSure).on('click',function(){
							video.play();
						});
					} else {
						$(exercisesLis).removeClass(exercisesChecked);
						$(this).addClass(exercisesChecked);
						$(exercisesAnswerCorrect).hide();
						$(exercisesAnswerError).show();
					};
				});
			};

			//章节弹出与收起
			o.toggleChapter = function(){
				var isShow = o.isChapterVisible(),
					sectionList_w = $sectionList.width();
				if(isShow){
					shapterVisible = false;
					o.setFancyPlayerBoxSize();
					$sectionList.animate({'right':'-' + sectionList_w + 'px'});
				} else {
					shapterVisible = true;
					o.setFancyPlayerBoxSize();
					$sectionList.animate({'right':'0px'});
				};
			};
			$chapter.on('click',function(){o.toggleChapter()});

			//初始化章节显示还是隐藏
			if(o.sectionList == false){
				$sectionList.addClass(shapterHideClass);
			};

			//章节-当前状态是展开还是收起
			o.isChapterVisible = function(){
				var isVisible;
				shapterVisible ? isVisible = true : isVisible = false;
				//console.log(isVisible);
				return isVisible;
			};

			//收藏与不收藏
			o.toggleAttention = function(e){
				var $this = e.target;
				$($this).toggleClass('active');
			};
			$collect.on('click','.acon',function(e){o.toggleAttention(e)});

			//获取fancyplayer播放区域宽高
			o.getFancyPlayerBoxSize = function(){
				var isShow = o.isChapterVisible(),
					windowSize = o.getWindowSize(),
					win_h = windowSize["height"],
					win_w = windowSize["width"],
					header_h = $header.height(),
					sectionList_w = $sectionList.width(),
					fancyPlayerBoxSize = {},
					fancyPlayerBox_h = '',
					fancyPlayerBox_w = '';
				isShow ? fancyPlayerBox_w = win_w - sectionList_w : fancyPlayerBox_w = win_w;
				fancyPlayerBox_h = win_h - header_h - o.getNum("80px");
				fancyPlayerBoxSize = {"width":'100%',"height":'100%'};
				//console.log(fancyPlayerBox_w);
				return fancyPlayerBoxSize;
			};
			//fancyplayer播放区域宽高变动
			o.setFancyPlayerBoxSize = function(){
				var fancyPlayerBoxSize = o.getFancyPlayerBoxSize(),
					fancyPlayerBox_w = fancyPlayerBoxSize.width,
					fancyPlayerBox_h = fancyPlayerBoxSize.height;
					isVideo = o.hasParam("video",o.player);
				//console.log(fancyPlayerBox_w);
				$fancyPlayerBox.css({'width':fancyPlayerBox_w,'height':fancyPlayerBox_h});
				if(o.isVersionBelowNine()){
					$sectionList.css('height',fancyPlayerBox_h + 'px');
					$sectionWrap.css('height',fancyPlayerBox_h + 'px');
				}
				if (isVideo) o.setVideoSize(fancyPlayerBox_w,fancyPlayerBox_h);
			};

			//获取video宽高
			/*o.getVideoSize = function(){
				var fancyPlayerBoxSize = o.getFancyPlayerBoxSize(),
					videoSize = {"width":fancyPlayerBoxSize.width,"height":fancyPlayerBoxSize.height};
				return videoSize;
			};*/
			//video宽度的变动
			o.setVideoSize = function (w,h){
				setTimeout(function(){
					var $videoContainer = $('.mejs-video'),//video容器
						$videoPlaypauseBtn = $('.mejs-playpause-button'),//播放按钮
						$videoCurrentTime = $('.mejs-currenttime'),//当前播放时间
						$videoTimeRail = $('.mejs-time-rail'),//进度条外框
						$videoTimeSlider = $('.mejs-time-slider'),//进度条内容
						$videoDurationBtn = $('.mejs-duration-container'),//视频总时间
						$videoVolumeBtn = $('.mejs-volume-button'),//音量按钮
						$videoFullscreenBtn = $('.mejs-fullscreen-button'),//全屏按钮
						fancyPlayerBox_w = w,
						fancyPlayerBox_h = h,
						videoPlaypauseBtn_w = $videoPlaypauseBtn.outerWidth(),
						videoCurrentTime_w = $videoCurrentTime.outerWidth(),
						videoDurationBtn_w = $videoDurationBtn.outerWidth(),
						videoVolumeBtn_w = $videoVolumeBtn.outerWidth(),
						videoFullscreenBtn_w = $videoFullscreenBtn.outerWidth(),
						videoTimeRail_w = fancyPlayerBox_w - videoPlaypauseBtn_w - videoCurrentTime_w - videoDurationBtn_w - videoVolumeBtn_w - videoFullscreenBtn_w - 6;
						videoTimeSlider_w = videoTimeRail_w - 10;
					$videoContainer.css({'width':fancyPlayerBox_w + 'px','height':fancyPlayerBox_h});
					$videoTimeRail.css('width',videoTimeRail_w + 'px');
					$videoTimeSlider.css('width',videoTimeSlider_w + 'px');
					o.setFlashVideoSize();
				},100)
			};
			//IE6、7、8下video变成FLASH之后宽高的处理
			o.setFlashVideoSize = function(){
				if(o.isVersionBelowNine()){
					var flashVideo = $('.mejs-shim'),
						fancyPlayerBoxSize = o.getFancyPlayerBoxSize(),
						fancyPlayerBox_w = fancyPlayerBoxSize.width,
						fancyPlayerBox_h = fancyPlayerBoxSize.height;
					flashVideo.css({'width':fancyPlayerBox_w + 'px','height':fancyPlayerBox_h});
				};
			};
			//实时获取video播放时间点
			o.getVideoCurrentTime = function(){
				var currentTime = o.videoCurrentTime,
					intCurrentTime = parseInt(currentTime);
				//console.log("intCurrentTime:",intCurrentTime);
				return intCurrentTime;
			};
			//设置video时间点事件
			o.setVideoTimestampEvent = function(){
				if(o.pointTime){
					var timestampInterval = window.setInterval(function(){
						var currentTime = o.getVideoCurrentTime(),
							pointTime = o.pointTime,
							isMultiTime = o.hasParam(',',pointTime);
						if(isMultiTime){
							var multiPointTime = pointTime.split(","),
								multiPointTimeLength = multiPointTime.length,
								multiPointSeconds = [];
							for(var i=0;i<multiPointTimeLength;i++) {
								multiPointSeconds.push(o.convertTimeToSecond(multiPointTime[i]));
								pointTime = multiPointSeconds;
							}
						} else {
							pointTime = o.convertTimeToSecond(o.pointTime);
						};
						//console.log("currentTime:" + currentTime + " pointTime:" + pointTime);
						if((pointTime - currentTime) < 1){
							//console.log(pointTime);
							clearInterval(timestampInterval);
							var video = o.videoPlayer,
								popup = $('#TB_overlayBG');
							video.pause();
							o.exitFullscreen(video);
							popup.trigger('click');//收起其它弹出层
							exercisesClick.trigger('click');
						};
					},1000);
				}
			};
			//video退出全屏
			o.exitFullscreen = function(elem){
				var de = document;
				if (de.exitFullscreen) {
					de.exitFullscreen();
				} else if (de.msExitFullscreen) {
					de.msExitFullscreen();
				} else if (de.mozCancelFullScreen) {
					de.mozCancelFullScreen();
				} else if(de.oRequestFullscreen){
					de.oCancelFullScreen();
				} else if (de.webkitCancelFullScreen) {
					de.webkitCancelFullScreen();
				}
			};

			//HH:mm:ss转second
			o.convertTimeToSecond = function(t){
				var times = t.split(":"),
					timesLength = times.length,
					seconds;
				if(timesLength == 1){
					seconds = parseInt(times[0]);
				} else if(timesLength == 2){
					seconds = parseInt(times[0])*60 + parseInt(times[1]);
				} else if(timesLength == 3){
					seconds = parseInt(times[0])*60 + parseInt(times[1])*3600 + parseInt(times[2]);
				} else {
					return false;
				}
				return seconds;
			};

			//浏览器窗口宽高变动
			$window.resize(function(){
				o.setFancyPlayerBoxSize();
			});

			//获取屏幕的宽高
			o.getWindowSize = function(){
				//浏览器可视宽度+滚动条宽度
				//var win_w = window.innerWidth;ie8不支持window.innerWidth
				//window.screen.width;ie8支持
				var scrollBarSize = o.getScrollBarSize();
					scroll_w = scrollBarSize["width"],
					win_w = window.screen.width - scroll_w,
					win_h = $(window).height(),
					windowSize = {"width":win_w,"height":win_h};
				return windowSize;
			};

			//获取字符串中的数字
			o.getNum = function(string){
				var num = parseInt(string.replace(/[^0-9]+/g, ''));
				return num;
			};

			//获取滚动条宽度
			o.getScrollBarSize = function(){
				var scrollSize = {"width":17};
				return scrollSize;
			};

			//判断参数中是否具有某个值
			o.hasParam = function(c,p){//c:值;p:参数
				if(o.isArray(p)){
					//判断是否在数组中
					for(var i=0,k=p.length;i<k;i++){
						if(c == p[i]){
							return true;
						}
					};
				} else if (o.isString(p)){
					//判断是否在字符串中
					var pat = new RegExp(c);
					var exist = pat.test(p);
					return exist == true ? true : false;
				} else {
					// 如果不在参数中就会返回false
					return false;
				}
			};

			//判断参数类型
			o.isArray = function(obj){
				return (typeof obj=='object')&&obj.constructor==Array;
			};
			o.isString = function(str){
				return (typeof str=='string')&&str.constructor==String;
			};
			o.isNumber = function(obj){
				return (typeof obj=='number')&&obj.constructor==Number;
			};
			o.isDate = function(obj){
				return (typeof obj=='object')&&obj.constructor==Date;
			};
			o.isFunction = function(obj){
				return (typeof obj=='function')&&obj.constructor==Function;
			};
			o.isObject = function(obj){
				return (typeof obj=='object')&&obj.constructor==Object;
			};

			//判断是否是IE6、7、8浏览器，需针对flash做样式处理
			o.isVersionBelowNine = function(){
				var browser = o.getBrowserAndVersion();
				if(browser.type == 'ie' && browser.version < 9) return true;
			};

			//判断浏览器及浏览器版本
			o.getBrowserAndVersion = function(){
				var Browser = {};
				var ua = navigator.userAgent.toLowerCase();
				var s;
				//返回浏览器版本Browser.XXX
				(s = ua.match(/msie ([\d.]+)/)) ? Browser={'version' : s[1],'type' : 'ie'}:
				(s = ua.match(/firefox\/([\d.]+)/)) ? Browser={'version' : s[1],'type' : 'firefox'}:
				(s = ua.match(/chrome\/([\d.]+)/)) ? Browser={'version' : s[1],'type' : 'chrome'}:
				(s = ua.match(/opera.([\d.]+)/)) ? Browser={'version' : s[1],'type' : 'opera'}:
				(s = ua.match(/version\/([\d.]+).*safari/)) ? Browser={'version' : s[1],'type' : 'safari'} : 0;
				return Browser;
			};

			//初始化fancyplayer
			o.init();

		});

		return this;
	}
});

$.fn.extend({
	fancyplayer: $.fn.fancyPlayer
});

})(jQuery);
